/**
 * 新用户注册
 */

// 预定义
var seljob = "";
var departments;// 部门列表
var jobs;// 职位列表

//页面载入初始化
$( "body" ).ready( function( e )
				   {
					   //init();

					   if( $( "#department" ).length > 0 )
					   {
						   $( "#department" ).bind( "change", departmentChanged );
						   initSelectJob( seljob, "department", "job" );
					   }

					   $( ".submit" ).bind( "click", submit );
					   $( "body" ).bind( "keyup", function( e )
					   {
						   if( e.which == 13 )
							   submit();
					   } );
				   } );

//初始化选定当前对象的职位
function initSelectJob( key, departmentid, jobid )
{
	var par;

	if( key != "" )
	{
		var job = jobs[ key ];
		par = job.parent;

		// 部门选中
		$( "#" + departmentid + " option[value=" + job.parent + "]" ).attr( "selected", true );
	}
	else
	{
		par = "jszb";
	}

	// 动态创建职位列表
	updateJobSelect( jobid, par, key );
}

function departmentChanged()
{
	var key = $( this ).val();
	updateJobSelect( "job", key, seljob );
}

function updateJobSelect( jobid, pid, key )
{
	var j = $( "#" + jobid );

	// 动态创建职位列表，每次创建前先清空历史条目
	j.empty();
	for( k in jobs )
	{
		if( jobs[ k ].parent == pid )
		{
			j.append( "<option value='" + k + "'" + ( k == key ? "selected='selected'" : "" ) + ">"
					  + jobs[ k ].name + "</option>" );
		}
	}
}

function submit()
{
	var data = {};

	data.nickname = $( "#nickname" ).val();
	data.job = $( "#job" ).val();
	data.region = $( "#region" ).val();
	data.usergroup = $( "#usergroup" ).val();
	data.qq_group_id = $("#qqgroup").val();
	data.username = $( "#username" ).val();
	data.password = $( "#password" ).val();
	data.repassword = $( "#repassword" ).val();
	
	if($( "#qqgroup" ).val()=="" || $( "#qqgroup" ).val()==null){
		alert("抱歉，请选择QQ分组！");
		return false;
	}
	
	if($( "#job" ).val()=="" || $( "#job" ).val()==null){
		alert("抱歉，职位不能为空！");
		return false;
	}
	if($( "#password" ).val()!=$( "#repassword" ).val()){
		alert("抱歉，两次密码不一样！");
		return false;
	}

	submitter.post( contextPath+"/index/addUser.json", data, function( d )
	{
		if( d.flag == 0 )
		{
			alert( "该登录名已经存在！" );
		}
		else
		{
			alert( "注册成功！" );
		}
	}, "json" );
}
